package com.htw.rv.fast_scroller.grid.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.htw.rv.fast_scroller.R
import com.htw.rv.fast_scroller.adapter.RvAdapterTextVH
import com.htw.rv.fast_scroller.adapter.RvItemData
import com.htw.rv.fast_scroller.databinding.LayoutRvGridItemBinding
import com.htw.rv.fast_scroller.databinding.LayoutRvItemTextBinding

class GridRvAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private val listData = ArrayList<RvItemData>()

    fun initListData() {
        for (index in 0..100) {
            val viewType = if (index % 10 == 1) 1 else 0
            val msg = if(viewType == 1) {
                "title data $index"
            } else {
                "this is test data $index"
            }
            listData.add(
                RvItemData(
                    R.mipmap.ic_launcher,
                    msg,
                    viewType
                )
            )
        }
    }

    fun getItemData(position: Int): RvItemData? {
        if (position < itemCount) {
            return listData[position]
        }
        return null
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            1 -> {
                RvAdapterTextVH(
                    LayoutRvItemTextBinding.inflate(
                        LayoutInflater.from(parent.context),
                        parent,
                        false
                    )
                )
            }
            else -> {
                GridRvAdapterVH(
                    LayoutRvGridItemBinding.inflate(
                        LayoutInflater.from(parent.context),
                        parent,
                        false
                    )
                )
            }
        }
    }

    override fun getItemViewType(position: Int): Int {
        return listData[position].itemViewType
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if(holder is RvAdapterTextVH) {
            holder.bind(listData[position])
        } else if(holder is GridRvAdapterVH) {
            holder.bind(listData[position])
        }
    }

    override fun getItemCount(): Int {
        return listData.size
    }
}